#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

HANDLE hCom1, hCom2;

void openPort(HANDLE *hCom, const char *portName) {
    *hCom = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (*hCom == INVALID_HANDLE_VALUE) {
        printf("Error opening port %s\n", portName);
        exit(1);
    }

    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    if (!GetCommState(*hCom, &dcbSerialParams)) {
        printf("Error getting COM state\n");
        CloseHandle(*hCom);
        exit(1);
    }

    dcbSerialParams.BaudRate = CBR_9600;
    dcbSerialParams.ByteSize = 8;
    dcbSerialParams.StopBits = ONESTOPBIT;
    dcbSerialParams.Parity = NOPARITY;

    if (!SetCommState(*hCom, &dcbSerialParams)) {
        printf("Error setting COM state\n");
        CloseHandle(*hCom);
        exit(1);
    }

    COMMTIMEOUTS timeouts = {0};
    timeouts.ReadIntervalTimeout = 50;
    timeouts.ReadTotalTimeoutConstant = 50;
    timeouts.ReadTotalTimeoutMultiplier = 10;
    timeouts.WriteTotalTimeoutConstant = 50;
    timeouts.WriteTotalTimeoutMultiplier = 10;
    if (!SetCommTimeouts(*hCom, &timeouts)) {
        printf("Error setting timeouts\n");
        CloseHandle(*hCom);
        exit(1);
    }
}

void closePort(HANDLE hCom) {
    CloseHandle(hCom);
}

void sendData(HANDLE hCom, char *data) {
    DWORD bytesWritten;
    if (!WriteFile(hCom, data, strlen(data), &bytesWritten, NULL)) {
        printf("Error writing to COM port\n");
    }
    else {
        printf("Sent: %s\n", data);
    }
}

void receiveData(HANDLE hCom) {
    char buffer[256];
    DWORD bytesRead;
    if (ReadFile(hCom, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) {
        buffer[bytesRead] = '\0';
        printf("Received: %s\n", buffer);
    }
    else {
        printf("Error reading from COM port\n");
    }
}

int main() {
    openPort(&hCom1, "COM1");
    openPort(&hCom2, "COM2");

    char * message = "Hello World!";

    sendData(hCom1, message);

    receiveData(hCom2);

    closePort(hCom1);
    closePort(hCom2);

    return 0;
}
